﻿/*-----------------------------------------------------------------------
 * <copyright file="SetSvInforCtrl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun </author>
 * <summary>
 *          SV信息管理     
 * 
 *  开始日期: 2010-10-18 09:09:05
 *  作成日:   2010-11-03
 * </summary>
 *----------------------------------------------------------------------- 
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.CompetenceSetPaeg.SetSvInfor
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;

    public partial class SetSvInforCtrl : UserControl
    {
        #region 全局变量
       
        /// 当前页面的名字（日志用）
        /// </summary>
        private const string ctrlName = " - SV管理页面 - ";

        /// <summary>
        /// 消息子窗体 errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox = null;

        /// <summary>
        /// 日志服务定义
        /// wcfLogClient
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient = null;

        /// <summary>
        ///  SV信息服务 引用
        /// </summary>
        private WCFServers.WCFAccountsRef.WCFAccountsClient svInfoClinet = null;

        /// <summary>
        /// 查找已分组的SV或SSV信息 的数据源
        /// </summary>
        private List<WCFServers.WCFAccountsRef.AccountInforBase> groupedList = null;

        /// <summary>
        /// 查找未分组的SV或SSV信息 的数据源
        /// </summary>
        private List<WCFServers.WCFAccountsRef.AccountInforBase> nogroupedList = null;

        /// <summary>
        /// 是否点击过DAGARID（gSVInfoNonList）里的记录
        /// </summary>
        bool isFirstRecordA = true;

        /// <summary>
        /// 是否点击过DAGARID（dgSVInfoList）里的记录
        /// </summary>
        bool isFirstRecordB = true;

        /// <summary>
        /// 存组信息
        /// </summary>
        List<string[]> FieldUnit = null;

        #endregion 全局变量

        /// <summary>
        /// SV权限管理
        /// </summary>
        public SetSvInforCtrl()
        {
            InitializeComponent();
            this.InitField();
            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.Loaded += new RoutedEventHandler(SetSvInforCtrl_Loaded);

            //查找已/未分组的SV或SSV信息 （服务）
            this.svInfoClinet.SvGroupUnitListCompleted += new EventHandler<WCFServers.WCFAccountsRef.SvGroupUnitListCompletedEventArgs>(svInfoClinet_SvGroupUnitListCompleted);

            //查找SV详细信息-组信息（服务）
            this.svInfoClinet.SvDetailedInfoListCompleted += new EventHandler<WCFServers.WCFAccountsRef.SvDetailedInfoListCompletedEventArgs>(svInfoClinet_SvDetailedInfoListCompleted);

            //DataGrid行选 事件
            this.dgSVInfoNonList.SelectionChanged += new SelectionChangedEventHandler(DataGrid_SelectionChanged);
            this.dgSVInfoList.SelectionChanged += new SelectionChangedEventHandler(DataGrid_SelectionChanged);

            //搜索按钮
            this.btnSearch.Click += new RoutedEventHandler(btnSearch_Click);

            //搜索框的提示文字
            FunctionClass.SetToolTipText(this.tbSearchText, PlacementMode.Mouse, "可以按用户ID模糊或精确查找！");
            //组的提示文字
            FunctionClass.SetToolTipText(this.tbGroupNum, PlacementMode.Mouse, "添加组，或是删除已存在的组！");

            //添加组
            this.btnUnitAdd.Click += new RoutedEventHandler(btnUnitAdd_Click);
            //添加组（服务）
            this.svInfoClinet.SvGroupAddCompleted += new EventHandler<WCFServers.WCFAccountsRef.SvGroupAddCompletedEventArgs>(svInfoClinet_SvGroupAddCompleted);
            
            //删除组
            this.btnUnitDel.Click += new RoutedEventHandler(btnUnitDel_Click);
            //删除组（服务）
            this.svInfoClinet.SvGroupDelCompleted += new EventHandler<WCFServers.WCFAccountsRef.SvGroupDelCompletedEventArgs>(svInfoClinet_SvGroupDelCompleted);
            
            //修改用户名
            this.btnRename.Click += new RoutedEventHandler(btnRename_Click);
            //改名（服务）
            this.svInfoClinet.ReNameCompleted += new EventHandler<Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef.ReNameCompletedEventArgs>(svInfoClinet_ReNameCompleted);

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));


             //判断用户身份，判断按钮是否可用
            if(FunctionClass.GetUserIdentity()!=FunctionClass.UserIdentity .ADMIN.ToString())
            {
                this.tbSearchText.IsEnabled = false;
                this.btnSearch.IsEnabled = false;

                this.tbGroupNum.IsEnabled = false;
                this.btnUnitAdd.IsEnabled = false;
                this.btnUnitDel.IsEnabled = false;
                
                this.dgSVInfoNonList.IsEnabled = false;
                this.dgSVInfoList.IsEnabled = false;
                this.dgUnitInfoList.IsEnabled = false;
            }
        }


        #region 修改用户名
        /// <summary>
        /// 修改用户名
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void btnRename_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.tbUserName.Text) || string.IsNullOrEmpty(this.tbUserID.Text)) 
            {
                FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      1,
                      "提示",
                      this.tbUserID.Tag +" 或 "+this.tbUserName.Tag + " 值不能为空!",
                      Colors.Gray,
                      true,
                      Visibility.Visible,
                      Visibility.Collapsed);
                return;
            }

            this.svInfoClinet.ReNameAsync(this.tbUserID.Text.Trim(), this.tbUserName.Text.Trim());
        }

        /// <summary>
        /// 修改用户名(服务实现)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void svInfoClinet_ReNameCompleted(object sender, Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFAccountsRef.ReNameCompletedEventArgs e)
        {
            try 
            {
                if (e.Error == null) 
                {
                    if (e.Result)
                    {
                        //已分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(null, true);
                        //未分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(null, false);

                        FunctionClass.ShowMessageBox(
                                 this.errorMessbox,
                                 1,
                                 "提示",
                                 "修改成功！",
                                 Colors.Gray,
                                 true,
                                 Visibility.Visible,
                                 Visibility.Collapsed);
                    }
                    else
                    {
                        FunctionClass.ShowMessageBox(
                                 this.errorMessbox,
                                 1,
                                 "提示",
                                 "修改失败！",
                                 Colors.Gray,
                                 true,
                                 Visibility.Visible,
                                 Visibility.Collapsed);
                    }
                }
                else 
                { 
                }
            }
            catch 
            {

            }
        }

        #endregion 修改用户名

        #region 删除组
        /// <summary>
        /// 删除组
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void btnUnitDel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.tbUserID.Text) || string.IsNullOrEmpty(this.tbUserName.Text) ||
                    string.IsNullOrEmpty(this.tbGroupNum.Text) )
                {
                    throw new Exception("删除组输入的参数不全！");
                }

                this.svInfoClinet.SvGroupDelAsync(this.tbUserID.Text, this.tbUserName.Text, this.tbGroupNum.Text);
            }
            catch (Exception exce)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                ctrlName +
                                                exce.Message.ToString()
                                                );

                FunctionClass.ShowMessageBox(
                  this.errorMessbox,
                  1,
                  "提示",
                  exce.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 删除组（服务实现）
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void svInfoClinet_SvGroupDelCompleted(object sender, WCFServers.WCFAccountsRef.SvGroupDelCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    //删除成功，返回值为 TRUE
                    if (e.Result)
                    {
                        //已分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), true);
                        //未分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), false);
                        
                        //显示组信息
                        if (!string.IsNullOrEmpty(this.tbUserID.Text))
                        {
                            this.svInfoClinet.SvDetailedInfoListAsync(this.tbUserID.Text);
                        }

                        throw new Exception(this.tbUserName.Text + " 删除组成功！");
                    }
                    else
                    {
                        throw new Exception(this.tbUserName.Text + " 删除组失败！");
                    }
                }
                else
                {
                    throw new Exception("svInfoClinet_SvGroupDelCompleted服务返回值有错！" + e.Error.Message.ToString());
                }

            }
            catch (Exception exce)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                               ctrlName +
                                               exce.Message.ToString() +
                                               this.tbGroupNum.Text + "组"
                                               );
                this.tbGroupNum.Text = string.Empty;

                FunctionClass.ShowMessageBox(
                  this.errorMessbox,
                  1,
                  "提示",
                  exce.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        #endregion 删除组

        #region 添加组
        /// <summary>
        /// 添加组
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void btnUnitAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if(string.IsNullOrEmpty(this.tbUserID.Text) || string.IsNullOrEmpty(this.tbUserName.Text)||
                    string.IsNullOrEmpty(this.tbGroupNum.Text) || string.IsNullOrEmpty(this.tbIsGroup.Text))

                {
                    throw new Exception("添加组输入的参数不全！");
                }
                
                //是否分组标记
                bool isGrouped=false;

                if(this.tbIsGroup.Text.ToString().ToUpper()=="TRUE")
                {
                    isGrouped=true;
                    //如果已分组，判断新加组是否和已有组重复
                    foreach (string[] groupNum in this.FieldUnit) 
                    {
                        if (groupNum[0] == this.tbGroupNum.Text) 
                        {
                            throw new Exception("添加的组，已存在！");
                        }
                    }
                }
                
                this.tbIsGroup.Text = string.Empty;
                this.svInfoClinet.SvGroupAddAsync(this.tbUserID.Text, this.tbUserName.Text, this.tbGroupNum.Text, isGrouped);
            }
            catch (Exception exce) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                               ctrlName +
                                               exce.Message.ToString()
                                               );

                FunctionClass.ShowMessageBox(
                  this.errorMessbox,
                  1,
                  "提示",
                  exce.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 添加组(服务实现)
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void svInfoClinet_SvGroupAddCompleted(object sender, WCFServers.WCFAccountsRef.SvGroupAddCompletedEventArgs e)
        {
            try 
            {
                if (e.Error == null) 
                {
                    //添加成功，返回值为 TRUE
                    if (e.Result)
                    {
                        //已分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), true);
                        //未分组SV
                        this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), false);

                        //显示组信息
                        if (!string.IsNullOrEmpty(this.tbUserID.Text))
                        {
                            this.svInfoClinet.SvDetailedInfoListAsync(this.tbUserID.Text);
                        }

                        throw new Exception(this.tbUserName.Text + " 添加组成功！");

                    }
                    else 
                    {
                        throw new Exception(this.tbUserName.Text + " 添加组失败！");
                    }
                }
                else 
                {
                    throw new Exception(" svInfoClinet_SvGroupAddCompleted 服务返回值有错！ " + e.Error.Message.ToString());
                }
            }
            catch (Exception exce) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                              ctrlName +
                                              exce.Message.ToString() +
                                              this.tbGroupNum.Text + "组"
                                              );
                this.tbGroupNum.Text = string.Empty;

                FunctionClass.ShowMessageBox( 
                  this.errorMessbox,
                  1,
                  "提示",
                  exce.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        #endregion 添加组

        #region 搜索按钮
        /// <summary>
        /// 搜索按钮
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            //已分组SV
            this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), true);
            //未分组SV
            this.svInfoClinet.SvGroupUnitListAsync(this.tbSearchText.Text.Trim(), false);
        }
        #endregion 搜索按钮

        #region DataGrid相关

        /// <summary>
        /// DataGrid行选 事件
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                #region DataGrid_SelectionChanged

                ///DataGrid默认第一条记录的SelectedIndex == 0，
                ///所以当只有一条记录时，不能引发DataGrid_SelectionChanged事件
                if (this.dgSVInfoNonList.SelectedIndex == 0 && !isFirstRecordA) 
                {
                    this.dgSVInfoNonList.SelectedIndex = -1;
                }
                isFirstRecordA = !isFirstRecordA;

                if (this.dgSVInfoList.SelectedIndex == 0 && !isFirstRecordB)
                {
                    this.dgSVInfoList.SelectedIndex = -1;
                }
                isFirstRecordB = !isFirstRecordB;

                #endregion DataGrid_SelectionChanged


                var selectData = e.AddedItems[0] as WCFServers.WCFAccountsRef.AccountInforBase;

                if (selectData != null)
                {
                    this.tbUserID.Text = selectData.AccountID.ToString();
                    this.tbUserName.Text = selectData.OpName.ToString();
                    this.tbIsGroup.Text = selectData.ParentID.ToString();

                    this.svInfoClinet.SvDetailedInfoListAsync(selectData.AccountID.ToString());
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                //索引超界
                return;
            }
        }

        /// <summary>
        /// 查找SV详细信息-组信息（实现）
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void svInfoClinet_SvDetailedInfoListCompleted(object sender, WCFServers.WCFAccountsRef.SvDetailedInfoListCompletedEventArgs e)
        {
            try
            {
                FieldUnit = new List<string[]>();
                if (e.Error == null)
                {
                    // 把回传值的组信息分离，传给dgUnitInfoList。
                    if (e.Result.Count > 0)
                    {
                        WCFServers.WCFAccountsRef.AccountData objclass = e.Result[0] as WCFServers.WCFAccountsRef.AccountData;

                        if (!string.IsNullOrEmpty(objclass.AccountState))
                        {
                            string[] strNum;
                            foreach (WCFServers.WCFAccountsRef.AccountData obj in e.Result)
                            {
                                strNum = new string[1];
                                strNum[0] = obj.AccountState.ToString();
                                FieldUnit.Add(strNum);
                            }
                        }
                        this.dgUnitInfoList.ItemsSource = null;
                        //组信息绑定
                        if (FieldUnit != null)
                        {
                            this.dgUnitInfoList.ItemsSource = FieldUnit;
                        }
                    }
                    else
                    {
                        this.dgUnitInfoList.ItemsSource = null;

                        this.tbUserID.Text = string.Empty;
                        this.tbUserName.Text = string.Empty;
                    }
                }
                else
                {
                    throw new Exception(" svInfoClinet_SvDetailedInfoListCompleted服务返回值有错！ " + e.Error.Message.ToString());
                }
            }
            catch (Exception exce)
            {
                this.dgUnitInfoList.ItemsSource = null;

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                              ctrlName +
                              exce.Message.ToString() 
                              );
                return;
            }
        }
        #endregion DataGrid相关

        #region 查找已/未分组的SV或SSV信息
        /// <summary>
        /// 查找已/未分组的SV或SSV信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void svInfoClinet_SvGroupUnitListCompleted(object sender,WCFServers.WCFAccountsRef.SvGroupUnitListCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null) 
                {
                    if (e.Result.Count > 0)
                    {
                        for (int i = 0; i < 1; i++)
                        {
                            WCFServers.WCFAccountsRef.AccountInforBase objclass = e.Result[i] as WCFServers.WCFAccountsRef.AccountInforBase;
                            //已分组
                            if (objclass.AccountID.Equals("TRUE"))
                            {
                                this.groupedList.Clear();
                                //返回值第一条记录是用于判断已/未分组的标记
                                for (int x = 1; x < e.Result.Count; x++)
                                {
                                    this.groupedList.Add(e.Result[x] as WCFServers.WCFAccountsRef.AccountInforBase);
                                }
                            }
                            //未分组
                            else
                            {
                                this.nogroupedList.Clear();
                                //返回值第一条记录是用于判断已/未分组的标记
                                for (int x = 1; x < e.Result.Count; x++)
                                {
                                    this.nogroupedList.Add(e.Result[x] as WCFServers.WCFAccountsRef.AccountInforBase);
                                }
                            }

                            //绑定相应的DataGrid
                            this.dgSVInfoNonList.ItemsSource = null;
                            this.dgSVInfoList.ItemsSource = null;

                            this.dgSVInfoNonList.ItemsSource = nogroupedList;
                            this.dgSVInfoList.ItemsSource = groupedList;
                        }
                    }
                    else
                    {
                        //没有相应的记录，不做任何处理
                    }
                }
                else
                {
                    throw new Exception(" svInfoClinet_SvGroupUnitListCompleted服务返回值有错！ " + e.Error.Message.ToString());
                }
            }
            catch (Exception exce) 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                              ctrlName +
                              exce.Message.ToString() 
                              );
                return;
            }
        }
        #endregion 查找相应的SV信息

        #region 变量初始化
        /// <summary>
        /// 变量初始化
        /// </summary>
        private void InitField()
        {
            this.errorMessbox = new childWindow.MessageBox();
            this.wcfLogClient = new WCFLog4Ref.WCFLog4Client();
            this.svInfoClinet = new WCFServers.WCFAccountsRef.WCFAccountsClient();
            this.groupedList = new List<WCFServers.WCFAccountsRef.AccountInforBase>();
            this.nogroupedList = new List<WCFServers.WCFAccountsRef.AccountInforBase>();
        }
        #endregion 变量初始化

        #region 页面Loaded
        /// <summary>
        /// 页面Loaded
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void SetSvInforCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //已分组SV
                this.svInfoClinet.SvGroupUnitListAsync(null, true);
                //未分组SV
                this.svInfoClinet.SvGroupUnitListAsync(null, false);
            }
            catch 
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                              ctrlName +
                              "页面初始化错误！"
                              );

                FunctionClass.ShowMessageBox(
                 this.errorMessbox,
                 1,
                 "提示",
                 "页面初始化错误！",
                 Colors.Gray,
                 true,
                 Visibility.Visible,
                 Visibility.Collapsed);

                return;
            }
        }
        #endregion 页面Loaded

        
    }
}
